package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Accessors(chain = true)
public class HrUnioinIdUtils {

    String HR_API_BASE_URL="";
    String signkey;
    String secretKey;

    public  String postForm(String url,Map<String,Object> data) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
                .setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("DataEncoding", "UTF-8");

        CloseableHttpResponse httpResponse = null;
        try {
            if(data!=null){
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
                formEntity.setContentType("Content-Type:application/x-www-form-urlencoded");
                httpPost.setEntity(formEntity);
            }
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public  String getUnionIdByHrTk(String tk){
        Map<String,Object> data=new HashMap<>();
        data.put("sign", getM5d(getM5d(tk)+signkey));
        data.put("tk",tk);

        String result= postForm(this.HR_API_BASE_URL,data);
        String unionId="";

        try {
            JsonNode jsonNode= new Jackson2ObjectMapperBuilder().build().readTree(result);
            Integer code=jsonNode.get("code").asInt();
            unionId=jsonNode.get("data").asText().trim();
            switch (code){
                case 200:
                    unionId= decryptDESFromBase64(unionId,secretKey);
                    if(unionId.contains("none:")){
                        String userId= unionId.split(":")[1];
                        System.out.println("对方没有unionId 提供了业务用户id "+userId);
                    }else{
                        System.out.println("成功获取到unionId "+unionId);
                    }
                    break;
                default:
                    String errorMsg=unionId;
                    System.out.println("调用出错 "+errorMsg);
                    //值会有这些
                    //sign invalid  签名出错
                    //tk invalid token错误或者失效
                    break;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return unionId;

    }



    private  byte[] decryptDES(byte[] src, String secretKey) {

        byte[] bytes=null;
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(secretKey.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, securekey, random);
            bytes=cipher.doFinal(src);
        }catch (Exception e){
            bytes=null;
        }

        return bytes;
    }

    private   String decryptDESFromBase64(String src, String secretKey) {
        byte[] bytes=null;
        String res="";
        try {
            bytes= Base64.decodeBase64(src);
            bytes=decryptDES(bytes,secretKey);
            res=new String(bytes,"utf-8");
        }catch (Exception e){
        }
        return res;
    }

    private   String getM5d(String conten)  {

        conten=(conten==null?"":conten);
        String md5="";
        try {
            md5= DigestUtils.md5Hex(conten.getBytes("utf-8"));
        }catch (Exception e){
            md5= DigestUtils.md5Hex(conten.getBytes());
        }

        return md5;
    }

}
